package de.bazinga.rotw.map;

import java.io.File;
import java.util.Hashtable;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class MapList {

	private static MapList instance = null;

	private static Document document = null;
	
	private Vector<Hashtable<String,String>> levels = null;
	
	public MapList() {
		// Get Levels
		levels = new Vector<Hashtable<String,String>>();
		
		File[] levelDirs = new File("levels/").listFiles();
		for(File lvlDir:levelDirs) {
			if(lvlDir.isDirectory()) {
				File info = new File(lvlDir.getAbsoluteFile()+"/levelInfo.xml");
				if(info.exists()) {
					// Is a level
					Hashtable<String,String> infoData = getLevelInfo(info);
					infoData.put("path", lvlDir.getAbsolutePath());
					
					levels.add(infoData);
				}
			}
		}
	}
	
	public static MapList getInstance() {
		if(instance == null) instance = new MapList();
		return instance;
	}
	
	public Vector<Hashtable<String,String>> getMapList() {		
		return levels;
	}
	
	private Hashtable<String,String> getLevelInfo(File infoFile) {
		// Load XML
		try{
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			document = builder.parse(infoFile);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		Hashtable<String,String> info = new Hashtable<String,String>();
		
		NodeList nodeList = document.getElementsByTagName("levelinfo").item(0).getChildNodes();
		info.put("name", nodeList.item(1).getFirstChild().getNodeValue());
		info.put("description", nodeList.item(3).getFirstChild().getNodeValue());
		info.put("gameMode", document.getElementsByTagName("mode").item(0).getFirstChild().getNodeValue());
		
		return info;
	}
	
	public int getIndexByName(String name) {
		for(int i=0;i < levels.size();i++) {
			if(levels.get(i).get("name").equals(name)) {
				return i;
			}
		}
		return -1;
	}
}
